<?php
namespace Home\Controller;
use Think\Controller;
class CrmController extends CommunalController{
	/*
		联系人-列表 add by chenyan 2018-09-07
	*/
	public function contact_list(){
		parent::check_permission('CRML-X');
		$job_level=$this->get_constant(C("JOB_LEVEL"));
		$relation=$this->get_constant(C("DECISION_RELATION"));
		$province_list=$this->get_province_city();
		if(!empty($_REQUEST['project_id'])){$pid=$_REQUEST['project_id'];}else{$pid="";}
		if(!empty($_REQUEST['check_project_id'])){$cpid=$_REQUEST['check_project_id'];}else{$cpid="";}
		if(!empty($_REQUEST['type'])){$type=$_REQUEST['type'];}else{$type=1;}
		
		$db_contact = M("db_crm_contact");
		if(!empty($_REQUEST['keyword'])){
			$keyword=$_REQUEST['keyword'];
			$mapp['db_project.project_num']=array('like','%'.$_REQUEST['keyword'].'%');
			$mapp['db_project.project_name']=array('like','%'.$_REQUEST['keyword'].'%');
			$mapp['db_crm_contact.username']=array('like','%'.$_REQUEST['keyword'].'%');
			$mapp['db_crm_contact.mobilephone']=array('like','%'.$_REQUEST['keyword'].'%');
			$mapp['_logic']='or';
			$where['_complex']=$mapp;
			$this->assign('keyword',$keyword);
		}
		
		if($pid!=""){//项目详情页关联
			$contact = $this->getContactInfoByProjectId($pid);
			$where['contact_id']=array('in',$contact);
			$type=2;
		}
		if($cpid!=""){//总列表查看
			$contact = $this->getContactInfoByProjectId($cpid);
			$where['contact_id']=array('in',$contact);
		}
		$field="contact_id,username,mobilephone,job,job_level,is_main,decision_relation,email";
		if(get_permission('CRML-X',3)){//个人查看
			$where['_string']='add_uid='.$this->login_id;
		}
        $result = $db_contact->field($field)->where($where)->order('add_date desc')->select();
		$project_list = $this->getProjectInfo();
		$job_list=C("JOB_LEVEL");
		$relation_list=C("DECISION_RELATION");
        foreach ($result as $key => $value){
			$result[$key]['project_name']=$this->getProjectNameByContactId($value['contact_id']);
			$value['job_level']==0?$jl="":$jl=$job_list[$value['job_level']];
			if($value['job']!=""){
				if($value['job_level']!=0){
					$result[$key]['jobinfo']=$value['job']."-".$jl;
				}else{
					$result[$key]['jobinfo']=$value['job'];
				}
			}else{
				$result[$key]['jobinfo']="";
			}
			$value['decision_relation']==0?$result[$key]['decision_relation']="":$result[$key]['decision_relation']=$relation_list[$value['decision_relation']];
		}
		$showlist = $this->show_page($result);
		$this->assign('job_level',$job_level);
		$this->assign('relation',$relation);
		$this->assign('province_list',$province_list);
		$this->assign('page',$showlist['show']);
		$this->assign('project_id',$pid);//有传pid会有对应的项目名和联系人
		$this->assign('check_project_id',$cpid);//总列表选中项目过滤
		$this->assign('type',$type);//标识总列表，还是项目详情列表1为总列表
		$this->assign('result',$showlist['result']);
		$this->assign('project_list',$project_list);
		$this->display();
	}
	/*
		联系人-添加 add by chenyan 2018-09-07
	*/
	public function contact_add(){
		parent::check_permission('CRML-X',NULL,1);
		//下拉框信息填充
		$typelist['job_level']=$this->get_constant(C("JOB_LEVEL"));
		$typelist['relation']=$this->get_constant(C("DECISION_RELATION"));
		$typelist['province_list']=$this->get_province_city();
		$res_project = M("db_crm_project")->where("del=1")->select();
		//项目进入
		if(!empty($_REQUEST['project_id'])){$pid=$_REQUEST['project_id'];}else{$pid="";}
		$add_data = array();
		if($_POST['username']){//提交信息
			$db_contact = M("db_crm_contact");
			if($_POST['project_id']){//存在项目值
				$pid=$_POST['project_id'];
			}
			$add_data = $this->unset_null($_POST,$add_data);//清洗提交的空数据
            $add_data['add_uid'] = $_SESSION['dms_uid'];
            $add_data['add_user'] = $_SESSION['dms_username'];
            $add_data['add_date'] = date('Y-m-d H:i:s');
			//判定手机号或者座机号是否重复
            try {
                $last_id = $db_contact->add($add_data);

				if($pid!=""){
					//更新项目联系人
					$this->update_project_contact($pid,$last_id);
					$this->success("操作成功", __APP__ . "/Crm/contact_list/project_id/".$pid);
					die();
				}else{
					if($add_data['contact_project']!=""){
						foreach($add_data['contact_project'] as $p){
							$this->update_project_contact($p,$last_id);
						}
					}
					$this->success("操作成功", __APP__ . "/Crm/contact_list");
					die;
				}
            } catch
            (\Exception $e) {
                $this->error("操作失败", __APP__ . "/Crm/contact_list");
                die;
            }
		}
		$this->assign('res_project', $res_project);
		$this->assign('typelist',$typelist);
		$this->assign('project_id',$pid);
		$this->display();
	}
	public function contact_doadd(){
		parent::check_permission('CRML-X',NULL,1);
		$db_contact = M("db_crm_contact");
		if($_POST['action']=='add'){
			$add_data = $this->unset_null($_POST,$add_data);//清洗提交的空数据
			$add_data['add_uid'] = $_SESSION['dms_uid'];
			$add_data['add_user'] = $_SESSION['dms_username'];
			$add_data['add_date'] = date('Y-m-d H:i:s');
			$last_id = $db_contact->add($add_data);
			$this->update_project_contact($_POST['project_id'],$last_id);//更新联系人
		}elseif($_POST['action']=='edit'){
			$edit_data['contact_id']=$_POST['contact_id'];
			$edit_data = $this->unset_null($_POST,$edit_data);//清洗提交的空数据
			$last_id = $db_contact->save($edit_data);
		}
		if($last_id)
		{
			$data['username']=$add_data['username'];
			$data['contact_id']=$last_id;
			$data['status']=self::YES;
			$data['msg']='操作成功';
		}
		else
		{
			$data['status']=self::NO;
			$data['msg']='操作失败';
		}
		echo json_encode($data);die;
	}

	/*
		联系人-编辑 add by chenyan 2018-09-07
	*/
	public function contact_edit()
    {
		$old_contact=array();
		parent::check_permission('CRML-X',NULL,1);
		$typelist['job_level']=$this->get_constant(C("JOB_LEVEL"));
		$typelist['relation']=$this->get_constant(C("DECISION_RELATION"));
		$typelist['province_list']=$this->get_province_city();
		$res_project = M("db_crm_project")->where("del=1")->select();
		if(!empty($_REQUEST['project_id'])){$pid=$_REQUEST['project_id'];}else{$pid="";}
        $id = $_GET['contact_id'];
		$db_contact = M("db_crm_contact");
        $result = $db_contact->where("contact_id=$id")->find();
		//获取人绑定的项目
		$contact_ids = $this->getProjectInfoByContactId($id);
		if(!empty($contact_ids)){
			foreach($contact_ids as $ids){
				array_push($old_contact,$ids['project_id']);
			}
			$old = implode(',', $old_contact);
		}
        $this->assign('contact_project_ids', $contact_ids);
        $this->assign('old', $old);
		$typelist['city_list']=$this->get_province_city($result['province_id']);
        if (!empty($_POST)) {
			$edit_data = array();
			try{
				if($_POST['project_id']){//存在项目值
					$pid=$_POST['project_id'];
				}
				$edit_data = $this->unset_null($_POST,$edit_data);//清洗提交的空数据
				
				$contact_project = implode(',', $edit_data['contact_project']);
				$old_list = explode(',', $old);
				if($contact_project!=$edit_data['old']){//有变化修改
					foreach($old_list as $ol){
						$this->change_contact($ol,$edit_data['contact_id']);
					}
					foreach($edit_data['contact_project'] as $p){
						$this->update_project_contact($p,$edit_data['contact_id']);
					}
				}
				$db_contact->save($edit_data);
				if($pid!=""){
					$this->success("操作成功", __APP__ . "/Crm/contact_list/project_id/".$pid);
					die();
				}
				//更新成功，编辑人与项目的关系
				
				$this->success('修改成功',__APP__."/Crm/contact_list");die;
            }catch (\Exception $e){
                // $this->add_log('修改收款计划失败','');
				$this->error("操作失败", __APP__ . "/Crm/contact_edit/contact_id/{$id}");
            }
        }
		$this->assign('res_project', $res_project);
        $this->assign('result', $result);
        $this->assign('contact_id', $id);
		$this->assign('project_id',$pid);
		$this->assign('typelist',$typelist);
        $this->display();
    }
	/*
		联系人-详情 add by chenyan 2018-09-07
	*/
	public function contact_detail(){
		$db_crm_contact=M('db_crm_contact');
		$where['contact_id']=$_REQUEST['contact_id'];
		$data=$db_crm_contact->where($where)->find();
		$job_level_list=C("JOB_LEVEL");

		$relation=C("DECISION_RELATION");
		$province_list=$this->get_province_city();
		$city_list=$this->get_province_city($data['province_id']);
		foreach($city_list as $k=>$cl){
			if($data['city_id']==$cl['id']){
				$city_name=$cl['name'];
			}
		}

		foreach ($data as $k=>$d){
			if($k=="is_main"){$d==1?$data['is_main']="<font color='red'>是</font>":$data['is_main']="否";}
			if($k=="gender"){$d==1?$data['gender']="男":$data['gender']="女";}
			// if($k=="job_level"){$d==0?$jl="":$jl=$job_level_list[$d];}
			// if($k=="job"){$d==0?$job="":$job=$d;}
			if($data['job']!=""){
				if($data['job_level']!=0){
					$data['jobinfo']=$data['job']."-".$job_level_list[$data['job_level']];
				}else{
					$data['jobinfo']=$data['job'];
				}
			}else{
				$data['jobinfo']="";
			}
			$data['addressInfo']=$province_list[$data['province_id']-1]['name'].$city_name.$data['address'];
			if($k=="decision_relation"){$d==0?$data['decision_relation']="":$data['decision_relation']=$relation[$d];}
			if($k=="email"){$d==""?$data['email']="":$data['email']=$d;}
		}
		echo json_encode($data);die;
	}
	/*
		市场信息-列表 add by chenyan 2018-09-10
	*/
	public function market_list(){
		parent::check_permission('CRMS-C');
		if(!empty($_REQUEST['channel'])){$get_channel=$_REQUEST['channel'];}else{$get_channel=-1;}
		$this->assign('get_channel',$get_channel);
		$db_information = M("db_crm_customers_information");
		//搜索条件
		if(!empty($_REQUEST['keyword']))
		{
			$map['customer_num']=array('like','%'.$_REQUEST['keyword'].'%');
			$map['customer_name']=array('like','%'.$_REQUEST['keyword'].'%');
			$map['_logic']='or';
			$where['_complex']=$map;
			$this->assign('keyword',$_REQUEST['keyword']);
		}
		if($get_channel!=-1){$where['channel']=$get_channel;}
		$where['del']=0;
		if(get_permission('CRMS-C',3)){//个人查看
			$where['_string']='add_uid='.$this->login_id;
		}

		$field="information_id,customer_num,customer_name,link_user,link_mobilephone,channel,project_id,add_uid";
        $result = $db_information->field($field)->where($where)->order('add_date desc')->select();
        $res_projects = M("db_crm_project")->field('project_id,project_num,information_id')->where("del=1")->select();
		$channel=$this->get_constant(C("PROJECT_SOURCE"));
        foreach ($result as $k => $value){
			$result[$k]['channel']=$channel[$value['channel']];
			foreach ($res_projects as $project){
			    if ($value['information_id'] == $project['information_id']){
                    $result[$k]['project_info'][] = $project;
                }
            }
            //注释无用代码 liubao 2018-11-26
			//if($value['project_id']==""){$result[$k]['project_info']['project_num']="";}else{$result[$k]['project_info']=$this->getProjectNameByInfoId($value['project_id']);}
		}
        $showlist = $this->show_page($result);
		$this->assign('channel',$channel);
		$this->assign('page',$showlist['show']);
		$this->assign('result',$showlist['result']);
		$this->display();
	}
	/*
		市场信息-添加 add by chenyan 2018-09-10
	*/
	public function market_add(){
		parent::check_permission('CRMS-C',NULL,1);
		//下拉框信息填充
		$channel=$this->get_constant(C("PROJECT_SOURCE"));
		$add_data = array();
		if($_POST['customer_name']){//提交信息
			$db_information = M("db_crm_customers_information");
			$add_data = $this->unset_null($_POST,$add_data);//清洗提交的空数据
			//添加市场信息编号
			$add_data['customer_num'] = $this->get_new_number();
            $add_data['add_uid'] = $_SESSION['dms_uid'];
            $add_data['add_user'] = $_SESSION['dms_username'];
            $add_data['add_date'] = date('Y-m-d H:i:s');
            try {
                $last_id = $db_information->add($add_data);
				//添加完毕市场信息-推送消息
				$Qywx = new \Qywx\Controller\IndexController();
                $title = $add_data['customer_name'];
                $description['stage'] = '发现新的需求';
                $description['leader'] = '负责人：' . $add_data['add_user'];
                $Qywx->push_card_message('stage1', $title, $description,"#");
                $this->success("操作成功", __APP__ . "/Crm/market_list");die;
            } catch
            (\Exception $e) {
                $this->error("操作失败", __APP__ . "/Crm/market_list");die;
            }
		}
		$this->assign('channel',$channel);
		$this->display();
	}
	/*
		市场信息-编辑 add by chenyan 2018-09-10
	*/
	public function market_edit(){
		parent::check_permission('CRMS-C',NULL,1);
		$channel=$this->get_constant(C("PROJECT_SOURCE"));
		$id = $_GET['information_id'];
		$db_information = M("db_crm_customers_information");
        $result = $db_information->where("information_id=$id")->find();
        if (!empty($_POST)) {
			$edit_data = array();
            try{
				$edit_data = $this->unset_null($_POST,$edit_data);//清洗提交的空数据
				$db_information->save($edit_data);
				$this->success('修改成功',__APP__."/Crm/market_list");die;
            }catch (\Exception $e){
                $this->add_log('修改市场信息失败','');
				$this->error("操作失败", __APP__ . "/Crm/market_list/information_id/{$id}");
            }
        }
        $this->assign('result', $result);
        $this->assign('information_id', $id);
		$this->assign('channel',$channel);
		$this->display();
	}
	/*
		市场信息-状态修改 add by chenyan 2018-09-10
	*/
	function customer_information_ajax(){
		$db_information = M("db_crm_customers_information");
		$re['information_id']=$_REQUEST['id'];
		$re['del']=1;//状态改成删除
		$result_bool=$db_information->save($re);
		if($result_bool)
		{
			$data['status']=self::YES;
			$data['msg']='操作成功';
		}
		else
		{
			$data['status']=self::NO;
			$data['msg']='操作失败';
		}
		echo json_encode($data);die;
	}
	/*
		市场信息-详情 add by chenyan 2018-09-10
	*/
	public function market_detail(){
		$db_information = M("db_crm_customers_information");
		$where['information_id']=$_REQUEST['id'];
		$data=$db_information->where($where)->find();
		$channel=$this->get_constant(C("PROJECT_SOURCE"));
		foreach ($data as $k => $d){
			if($k=="project_id"){$d==""?$data['project_info']="暂无":$data['project_info']=$this->getProjectNameByInfoId($d);}
			if($k=="channel"){$data['channel']=$channel[$d]['name'];}
		}
		echo json_encode($data);die;
	}
	/*
		跟进记录-列表
	*/
	public function follow_list(){
		parent::check_permission('CRMG-J');
		//年/周联动查询
		if(!empty($_REQUEST['year'])){
			$year=$_REQUEST['year'];
		}else{
			$year=-10;
		}
		$this->assign('year',$year);
		if($year==-10){
			$week=-10;
		}else{
			if(!empty($_REQUEST['week'])){
				$week=$_REQUEST['week'];
			}else{
				$week=-10;
			}
		}
		$this->assign('week',$week);
		if(!empty($_REQUEST['get_work'])){
			$get_work=$_REQUEST['get_work'];
		}else{
			$get_work=-10;
		}
		$this->assign('get_work',$get_work);
		if(!empty($_REQUEST['get_follow'])){
			$get_follow=$_REQUEST['get_follow'];
		}else{
			$get_follow=-10;
		}
		$this->assign('get_follow',$get_follow);
		if(!empty($_REQUEST['get_status'])){
			$get_status=$_REQUEST['get_status'];
		}else{
			$get_status=-10;
		}
		$this->assign('get_status',$get_status);
		if(!empty($_REQUEST['get_user'])){
			$get_user=$_REQUEST['get_user'];
		}else{
			$get_user=-10;
		}
		$this->assign('get_user',$get_user);
		if(!empty($_REQUEST['get_project'])){
			$get_project=$_REQUEST['get_project'];
		}else{
			$get_project=-10;
		}
		$this->assign('get_project',$get_project);
		if(intval(date('W'))==1){
			$whole_week=$this->get_year_month_week(5,date("Y")-1);
		}else{
			$whole_week=$this->get_year_month_week(5,date("Y"));
		}
		for($i=1;$i<=$whole_week;$i++)
		{
			$week_list[$i]['num']=$i;
			$week_list[$i]['detail']="第".$i."周";
		}
		$this->assign('week_list',$week_list);
		$this->assign("year_list",$this->get_year_month_week(1));
		if(!empty($_REQUEST['project_id'])){$pid=$_REQUEST['project_id'];}else{$pid="";}
		$this->assign('project_id',$pid);//有传pid会有对应的项目状态和联系人
		//关联项目
		$project = $this->getProjectInfo($pid);
		//联系人
		if($pid!=""){
			$contact = $this->getContactByProjectLinkman($project[0]['other_linkman']);
			$project_status = $project[0]['stage'];
		}else{
			$contact="";
			$project_status = "";
		}
		//跟进方式
		$follow_type=$this->get_constant(C("FOLLOW_TYPE"));
		//项目阶段
		$status=$this->get_constant(C("PROJECT_PHASE"));
		$work_chance = array("1"=>'顺利',"2"=>'一般',"3"=>'困难',"4"=>'不确定');
		$userList = get_userName('');
		$res_project = M("db_crm_project")->where("del=1")->select();
		$db_follow = M('db_crm_follow_record');
		$field="record_id,project_id,contact_id,follow_type,status,work_chance,work_type,visit_date,add_user,year,week,add_uid,add_date,remark";
		if($week!=-10){$where['week']=$week;}
		if($year!=-10){$where['year']=$year;}
		if($get_work!=-10){$where['work_chance']=$get_work;}
		if($get_follow!=-10){$where['follow_type']=$get_follow;}
		if($get_status!=-10){$where['status']=$get_status;}
		if($get_user!=-10){$where['add_uid']=$get_user;}
		if($get_project!=-10){$where['project_id']=$get_project;}
		if($pid!=""){$where['project_id']=$pid;}
		if(get_permission('CRMG-J',3)){//个人查看
			$where['_string']='add_uid='.$this->login_id;
		}
        $result = $db_follow->field($field)->where($where)->order('add_date desc')->select();
		$re = $db_follow->getLastSql();
		$db_answer=M('db_crm_follow_answer');
        foreach ($result as $k => $value){
			$projectlist = $this->getProjectInfo($value['project_id']);
			$result[$k]['project_name']=$projectlist[0]['name'];
			if($value['contact_id']!='' || $value['contact_id']!=0){
				$contactlist = $this->getContactByProjectLinkman($value['contact_id']);
				if($contactlist[0]['username']!=""){
					$result[$k]['customer_info']=$contactlist[0]['username']."(".$contactlist[0]['mobilephone'].")";
				}else{
					$result[$k]['customer_info']='';
				}
			}else{
				$result[$k]['customer_info']='';
			}
			$vd = explode(" ",$value['visit_date']);
			$result[$k]['visit_date']=$vd[0];
			// $result[$k]['work_type']=$this->get_work_type($value['work_type']);
			$timeInfo = $this->getNowTimeInfo($value['add_date']);
			$result[$k]['week_detail']="第".$value['week']."周（".$timeInfo['week_start']."至".$timeInfo['week_end']."）";
			$where_m['record_id']=$value['record_id'];
			$re = $db_answer->field("is_answer")->where($where_m)->find();
			$result[$k]['is_answer']=$re['is_answer'];
		}
		
		$showlist = $this->show_page($result);
		$this->assign('page',$showlist['show']);
		$this->assign('result',$showlist['result']);
		$this->assign('follow_type',$follow_type);
		$this->assign('work_chance',$work_chance);
		$this->assign('status',$status);
		$this->assign('project',$project);
		$this->assign('contact',$contact);
		$this->assign('user_list', $userList);
		$this->assign('res_project', $res_project);
		$this->assign('project_status',$project_status);
		
		$this->display();
	}
	/*
		工作类型赋值
		参数 替换值
	*/
	public function get_work_type($wt){
		$wt = str_replace("1","工作建议书",$wt);
		$wt = str_replace("2","计划书沟通",$wt);
		$wt = str_replace("3","合同沟通",$wt);
		$wt = str_replace("4","前期沟通",$wt);
		$wt = str_replace(",","<br>",$wt);
		return $wt;
	}
	/*
		跟进记录-添加(ajax)
	*/
	public function follow_ajax(){
		$db_follow = M('db_crm_follow_record');
		$db_project = M('db_crm_project');
		if($_REQUEST['action']=='add')
		{
			parent::check_permission('CRMG-J',NULL,1);
			$add_data = array();
			$add_data = $this->unset_null($_REQUEST,$add_data);//清洗提交的空数据
			$add_data['add_uid'] = $_SESSION['dms_uid'];
            $add_data['add_user'] = $_SESSION['dms_username'];
            $add_data['add_date'] = date('Y-m-d H:i:s');
			$now = date("Y-m-d");
			$timeInfo = $this->getNowTimeInfo($now);
			$add_data['year']=$timeInfo['year'];
			$add_data['week']=$timeInfo['week'];
			$add_data['year_week']=$timeInfo['year'].$timeInfo['week'];
			//更新upload表返回upload值
			if($add_data['file_url']){
				$db_project_upload = M('db_crm_project_upload');
				$where['project_id']=$add_data['project_id'];
				$where['name']=$add_data['file_name'];
				$where['file_url']=$add_data['file_url'];
				$where['file_date']= $add_data['add_date'];
				$url = explode("/",$add_data['file_url']);
				$where['file_name']= $url[5];
				$where['remark']= $add_data['remark'];
				$where['add_uid'] = $add_data['add_uid'];
				$where['add_date'] = $add_data['add_date'];
				$add_data['upload_id']=$last_id;
			}
			$result_bool=$db_follow->add($add_data);
			//更新流程表
			$this->update_project_flow($add_data['project_id'],$add_data['status'],$add_data['remark'],$add_data['add_uid'],$add_data['add_user'],$add_data['add_date']);
			//更新项目表状态
			$edit_project['project_id']=$add_data['project_id'];
			$edit_project['stage']=$add_data['status'];
			$db_project->save($edit_project);
		}
		elseif($_REQUEST['action']=='edit')
		{
			parent::check_permission('CRMG-J',NULL,1);
			//老的值比对文件是否变化
			$where_d['record_id']=$_REQUEST['id'];
			$result_d=$db_follow->where($where_d)->find();

			$edit_data = array();
			$edit_data['record_id']=$_REQUEST['id'];
			$edit_data = $this->unset_null($_REQUEST,$edit_data);//清洗提交的空数据
			if(!empty($_REQUEST['file_name'])){//有上传文件
				if($_REQUEST['file_url']){
					//判断是否修改过文件
					if($result_d['file_url']==""){
						if($edit_data['file_url']){
							$db_project_upload = M('db_crm_project_upload');
							$where['project_id']=$edit_data['project_id'];
							$where['name']=$edit_data['file_name'];
							$where['file_url']=$edit_data['file_url'];
							$where['file_date']= $edit_data['add_date'];
							$url = explode("/",$edit_data['file_url']);
							$where['file_name']= $url[5];
							$where['remark']= $edit_data['remark'];
							$where['update_uid'] = $_SESSION['dms_uid'];
							$where['update_date'] =  date('Y-m-d H:i:s');
							$last_id = $db_project_upload->add($where);
							$edit_data['upload_id']=$last_id;
						}
					}else{
						if($_REQUEST['file_url']!=$result_d['file_url']){
							//删除原文件
							$file1=str_replace("/dms_erp/uploads", "./uploads",$result_d['file_url']);
							if (file_exists($file1)){
								@unlink($file1);
							}
							//更新upload表
							if($edit_data['file_url']){
								$db_project_upload = M('db_crm_project_upload');
								$where['upload_id']=$result_d['upload_id'];
								$where['project_id']=$edit_data['project_id'];
								$where['name']=$edit_data['file_name'];
								$where['file_url']=$edit_data['file_url'];
								$where['file_date']= $edit_data['add_date'];
								$url = explode("/",$edit_data['file_url']);
								$where['file_name']= $url[5];
								$where['remark']= $edit_data['remark'];
								$where['update_uid'] = $_SESSION['dms_uid'];
								$where['update_date'] =  date('Y-m-d H:i:s');
								$db_project_upload->save($where);
							}
						}
					}
				}
			}else{//编辑时候剔除上传的文件（1.文件删除，2upload_id表中信息删除）
				if($result_d['file_url']){
					//删除原文件
					$file1=str_replace("/dms_erp/uploads", "./uploads",$result_d['file_url']);
					if(file_exists($file1)){
						@unlink($file1);
					}
				}
				$edit_data['upload_id']=NULL;
				//删除关联upload信息
				$this->delete_upload_ajax($result_d['upload_id']);
			}
			//更新项目状态
			$this->update_project_flow($edit_data['project_id'],$edit_data['status'],$edit_data['remark'],$edit_data['add_uid'],$edit_data['add_user'],$edit_data['add_date']);
			//更新项目表状态
			$edit_project['project_id']=$edit_data['project_id'];
			$edit_project['stage']=$edit_data['status'];
			$db_project->save($edit_project);
			$result_bool=$db_follow->save($edit_data);

		}
		if($result_bool)
		{
			$data['status']=self::YES;
			$data['msg']='操作成功';
		}
		else
		{
			$data['status']=self::NO;
			$data['msg']='操作失败';
		}
		echo json_encode($data);die;
	}
	/*
		根据项目获取对应的联系人
	*/
	public function project_follow_ajax(){
		$project = $this->getProjectInfo($_POST['id']);

		if($project[0]['other_linkman']!=""){
			$data['list'] = $this->getContactByProjectLinkman($project[0]['other_linkman']);
			if($project[0]['stage']!=""){
				$data['stage']=$project[0]['stage'];
			}else{
				$data['stage']=0;
			}
		}else{
			$data = array();
		}
		echo json_encode($data);die;
	}
	/*
		根据record_id获取对应的信息
	*/
	public function getInfoByRecordId(){
		$db_follow = M('db_crm_follow_record');
		$where['record_id']=$_REQUEST['id'];
		$re = $db_follow->where($where)->find();
		$vd = explode(" ",$re['visit_date']);//优化日期字段
		$re['visit_date']=$vd[0];
		$project = $this->getProjectInfo($re['project_id']);//子下拉联动
		$data = $this->getContactByProjectLinkman($project[0]['other_linkman']);
		$html = "<option value='-10'>请选择</option>";
		foreach($data as $d){
			if($d['contact_id']==$re['contact_id']){$select="selected";}else{$select="";}
			$html .= "<option value='".$d['contact_id']."' ".$select.">".$d['username']."</option>";
		}
		$re['contact_info']=$html;
		$re['file_name']=$this->getFileNameByUploadId($re['upload_id']);
		echo json_encode($re);die;
	}
	/*
		根据contact_id获取对应的信息
	*/
	public function getInfoByContactId(){
		$db_contact = M("db_crm_contact");
		$where['contact_id']=$_REQUEST['id'];
		$re = $db_contact->where($where)->find();
		$data=$this->get_province_city($re['province_id']);

		$html = "<option value='-10'>市</option>";
		foreach($data as $d){
			if($d['id']==$re['city_id']){$select="selected";}else{$select="";}
			$html .= "<option value='".$d['id']."' ".$select.">".$d['name']."</option>";
		}
		$re['city_info']=$html;
		echo json_encode($re);die;
	}
	
	/*
		根据upload_id获取对应的上传文件信息
		参数 upload_id 上传文件id
	*/
	public function getFileNameByUploadId($upload_id){
		$db_upload = M('db_crm_project_upload');
		$where['upload_id']=$upload_id;
		$re = $db_upload->field('name')->where($where)->find();
		return $re['name'];
	}
	/*
		删除upload表信息
	*/
	function delete_upload_ajax($upload_id){
		$db_crm_project_upload = M("db_crm_project_upload");
		$where['upload_id']=$upload_id;
		$result_bool=$db_crm_project_upload->where($where)->delete();
	}
	/*
		进程批复
	*/
	function follow_answer_ajax(){
		$db_follow = M('db_crm_follow_answer');
		$where['record_id']=$_REQUEST['id'];
		$where['answer_content']=$_REQUEST['answer_content'];
		if($_REQUEST['answer']==1){
			$where['is_answer']=2;
		}else{
			$where['is_answer']=1;
		}
		$where['add_uid'] = $_SESSION['dms_uid'];
		$where['add_user'] = $_SESSION['dms_username'];
        $where['add_date'] = date('Y-m-d H:i:s');
		$result_bool=$db_follow->add($where);
		if($result_bool)
		{
			$data['status']=self::YES;
			$data['msg']='批复完成';
		}
		else
		{
			$data['status']=self::NO;
			$data['msg']='操作失败';
		}
		echo json_encode($data);die;
	}
	/*
		项目详情--资料文件列表
	*/
	public function upload_list(){
		parent::check_permission('CRMG-J');
		$db_upload = M('db_crm_project_upload');
		if(!empty($_REQUEST['type'])){$type=$_REQUEST['type'];}else{$type=-10;}
		$this->assign('type',$type);
		$ptype_list=$this->library_type_list(6,24);
		$this->assign('ptype_list',$ptype_list[0]['second']);
		$where['project_id']=$_REQUEST['project_id'];
		$where['del']=0;
		$result = $db_upload->where($where)->order('add_date desc')->select();

		foreach($result as $key=>$value){
			$result[$key]['type_name']=$this->get_db_universal_label(2,$value['type']);
			$result[$key]['add_user']=$this->get_username($value['add_uid']);
			$result[$key]['update_user']=$this->get_username($value['update_uid']);
		}
		$this->assign('result',$result);
		$this->assign('project_id',$_REQUEST['project_id']);
		
		$this->display();
	}
	//项目功能-->项目过程文件-->ajax编辑数据 designed by:zhangsen 2017-09-14
	function project_files_ajax(){
		$db_project_uploads=M('db_crm_project_upload');
		$where['upload_id']=$_REQUEST['id'];
		$result=$db_project_uploads->where($where)->order('add_date desc')->find();
		echo json_encode($result);die;
	}
	/*
		项目详情--添加文件
	*/
	function project_files_status(){
		$db_project_uploads=M('db_crm_project_upload');
		$db_universal_label2=M('db_universal_label2');
		if($_REQUEST['action']=='add')
		{
			parent::check_permission('CRMG-J',NULL,1);
			if(!empty($_REQUEST['type_input']))
			{
				//新增项目分类
				$db_universal_label2=M('db_universal_label2');
				$where_center['first_id']=24;
				$where_center['second_name']=$_REQUEST['type_input'];
				$exist_center=$db_universal_label2->where($where_center)->find();
				if(!empty($exist_center))
				{
					$data['status']=self::NO;
					$data['msg']='该项目分类已存在！';
					echo json_encode($data);die;
				}
				$where_center_sort['first_id']=$where_center['first_id'];
				$where_center['first_sort']=$db_universal_label2->where($where_center_sort)->order('second_sort desc')->getField('second_sort')+1;
				$where_center['add_uid']=$this->login_id;
				$where_center['add_date']=date("Y-m-d H:i:s");
				$p_type_id=$db_universal_label2->add($where_center);
				$where['type']=$p_type_id;
			}else{
				$where['type']=$_REQUEST['type'];
			}
			$where['project_id']=$_REQUEST['pid'];
			$where['name']=$_REQUEST['name'];
			if(!empty($_REQUEST['file_name'])){$where['file_name']=$_REQUEST['file_name'];}
			if(!empty($_REQUEST['file_url'])){$where['file_url']=$_REQUEST['file_url'];}
			$where['file_date']=$_REQUEST['file_date'];
			if(!empty($_REQUEST['remark'])){$where['remark']=$_REQUEST['remark'];}
			$where['add_uid']=$this->login_id;
			$where['add_date']=date('Y-m-d H:i:s');
			$result_bool=$db_project_uploads->add($where);
		}
		elseif($_REQUEST['action']=='edit')
		{
			parent::check_permission('CRMG-J',NULL,1);
			$where_d['upload_id']=$_REQUEST['id'];
			$result_d=$db_project_uploads->where($where_d)->find();
			if(!empty($_REQUEST['type_input']))
			{
				//新增项目分类
				$db_universal_label2=M('db_universal_label2');
				$where_center['first_id']=24;
				$where_center['second_name']=$_REQUEST['type_input'];
				$exist_center=$db_universal_label2->where($where_center)->find();
				if(!empty($exist_center))
				{
					$data['status']=self::NO;
					$data['msg']='该项目分类已存在！';
					echo json_encode($data);die;
				}
				$where_center_sort['first_id']=$where_center['first_id'];
				$where_center['first_sort']=$db_universal_label2->where($where_center_sort)->order('second_sort desc')->getField('second_sort')+1;
				$where_center['add_uid']=$this->login_id;
				$where_center['add_date']=date("Y-m-d H:i:s");
				$p_type_id=$db_universal_label2->add($where_center);
				$where['type']=$p_type_id;
			}else{
				$where['type']=$_REQUEST['type'];
			}
			$where['upload_id']=$_REQUEST['id'];
			$where['project_id']=$_REQUEST['pid'];
			$where['name']=$_REQUEST['name'];
			if(!empty($_REQUEST['file_name'])){
				$where['file_name']=$_REQUEST['file_name'];
				if($_REQUEST['file_url']){
					//判断是否修改过文件
					if($_REQUEST['file_url']!=$result_d['file_url']){
						$where['file_url']=$_REQUEST['file_url'];
						//删除原文件
						$file1=str_replace("/dms_erp/uploads", "./uploads",$result_d['file_url']);
						if (file_exists($file1)){
							@unlink($file1);
						}
					}
				}else{
					$where['file_url']=NULL;
					if($result_d['file_url']){
						//删除原文件
						$file1=str_replace("/dms_erp/uploads", "./uploads",$result_d['file_url']);
						if(file_exists($file1)){
							@unlink($file1);
						}
					}
				}
			}else{
				$where['file_name']=NULL;
				$where['file_url']=NULL;
				if($result_d['file_url']){
					//删除原文件
					$file1=str_replace("/dms_erp/uploads", "./uploads",$result_d['file_url']);
					if(file_exists($file1)){
						@unlink($file1);
					}
				}
			}
			$where['file_date']=$_REQUEST['file_date'];
			if(!empty($_REQUEST['remark'])){$where['remark']=$_REQUEST['remark'];}else{$where['remark']=NULL;}
			$where['update_uid']=$this->login_id;
			$where['update_date']=date('Y-m-d H:i:s');
			$result_bool=$db_project_uploads->save($where);
		}
		elseif($_REQUEST['action']=='delete')
		{
			$where_d['upload_id']=$_REQUEST['id'];
			$result_d=$db_project_uploads->where($where_d)->find();
			//删除附件
			$url=$result_d['file_url'];
			$file=str_replace("/dms_erp/uploads", "./uploads",$url);
			if (file_exists($file)) {
				@unlink($file);
			}
			$where['upload_id']=$_REQUEST['id'];
			$where['del']=1;//状态改成删除不用物理删除
			$result_bool=$db_project_uploads->save($where);
			// $result_bool=$db_project_uploads->where($where)->delete();
		}
		if($result_bool)
		{
			$data['status']=self::YES;
			$data['msg']='操作成功';
		}
		else
		{
			$data['status']=self::NO;
			$data['msg']='操作失败';
		}
		echo json_encode($data);die;
	}
	/*数据映射 old 联系人到 new*/
	public function data_map_contract(){
		$db_old=M('db_project_contacts');
		$db_new=M('db_crm_contact');
		$result = $db_old->order("id asc")->select();
		foreach($result as $r){
			$list = array();
			$list['contact_id']=$r['id'];
			$list['username']=$r['username'];
			if($r['gender']=="男"){
				$list['gender']=1;
			}elseif($r['gender']=="女"){
				$list['gender']=2;
			}else{
				$list['gender']=NULL;
			}
			$list['mobilephone']=$r['mobilephone'];
			$list['company_name']=$r['company_name'];
			$list['telephone']=$r['telephone'];
			$list['job']=$r['job'];
			$list['qq']=$r['qq'];
			$list['email']=$r['email'];
			$list['remark']=$r['remark'];
			$list['add_uid']=$r['add_uid'];
			$list['add_user']=$r['add_user'];
			$list['add_date']=$r['add_date'];
			$list['province_id']=$r['province_id'];
			$list['city_id']=$r['city_id'];
			$list['address']=$r['address'];
			$db_new->add($list);
		}
		die("映射完毕!!!!");
	}

	/*数据映射 old 市场信息到 new*/
	public function data_map_market(){
		$db_old=M('db_customers_information');
		$db_new=M('db_crm_customers_information');
		$db_project_old = M('db_project');
		$channel_list=array('104'=>'4','105'=>'7','107'=>'10','95'=>'3','96'=>'6','97'=>'8','98'=>'8');
		$result = $db_old->order("id asc")->select();
		$list = array();
		foreach($result as $r){
			$list['information_id']=$r['id'];
			$list['customer_name']=$r['customer_name'];
			$where_p['info_id']=$r['id'];
			$dmap = $db_project_old->where($where_p)->find();
			$list['project_id']=$dmap['id'];
			$list['link_user']=$r['link_user'];
			$list['channel']=$channel_list[$r['channel']];
			$list['remark']=$r['channel_remark'];
			$list['customer_num']=$r['customer_num'];
			$list['add_uid']=$r['add_id'];
			$list['add_user']=$r['add_user'];
			$list['add_date']=$r['add_date'];
			$db_new->add($list);
		}
		die("映射完毕!!!!");
	}
	//获取联系人信息
    public function getCrmContact()
    {
        $res_crm_contact = M("db_crm_contact")->select();
        echo json_encode($res_crm_contact);
        die;
    }
	/* 数据映射 old db_project_progress 项目进展信息到 new db_crm_follow_record*/
	public function data_map_progress(){
		$db_old=M('db_project_progress');
		$db_new=M('db_crm_follow_record');
		$result = $db_old->order("id asc")->select();
		$list = array();
		foreach($result as $r){
			$list['project_id']=$r['pid'];
			$list['remark']=$r['progress'].$r['plan'];
			$list['add_uid']=$r['add_uid'];
			$list['add_date']=$r['add_date'];
			$list['status']=2;//项目阶段--商务谈判
			$list['work_type']=1;//工作类别--工作建议书
			$list['work_chance']=1;//商务机会--顺利
			$timeInfo = $this->getNowTimeInfo($r['add_date']);
			$list['year']=$timeInfo['year'];
			$list['week']=$timeInfo['week'];
			$list['year_week']=$timeInfo['year'].$timeInfo['week'];
			$db_new->add($list);
		}
		die("映射完毕!!!!data_map_progress");
	}
	/* 数据映射 old db_project_communicate 项目进展信息到 new db_crm_follow_record*/
	public function data_map_communicate(){
		$db_old=M('db_project_communicate');
		$db_new=M('db_crm_follow_record');
		$result = $db_old->order("id asc")->select();
		$list = array();
		foreach($result as $r){
			$list['project_id']=$r['pid'];
			$list['visit_date']=$r['date'];
			$list['add_uid']=$r['add_uid'];
			$list['add_date']=$r['add_date'];
			$list['file_name']=$r['file_name'];
			$list['file_url']=$r['file_url'];
			if($r['remark_text']!=""){
				$list['remark']=$r['remark_text'];
			}else{
				if($r['remark']!=""){
					$list['remark']=$r['remark'];
				}
			}
			$list['status']=2;//项目阶段--商务谈判
			$list['work_type']=2;//工作类别--计划书沟通
			$list['work_chance']=1;//商务机会--顺利
			$timeInfo = $this->getNowTimeInfo($r['add_date']);
			$list['year']=$timeInfo['year'];
			$list['week']=$timeInfo['week'];
			$list['year_week']=$timeInfo['year'].$timeInfo['week'];
			$db_new->add($list);
		}
		die("映射完毕!!!!communicate表");
	}
	/*数据映射 old 过程文件都 new*/
	public function data_map_upload(){
		$db_old=M('db_project_uploads');
		$db_new=M('db_crm_project_upload');
		$result = $db_old->order("id asc")->select();
		$list = array();
		foreach($result as $r){
			$list['upload_id']=$r['id'];
			$list['project_id']=$r['pid'];
			$list['remark']=$r['remart'];
			$list['file_name']=$r['file_name'];
			$list['file_url']=$r['file_url'];
			$list['file_date']=$r['file_date'];
			$list['add_uid']=$r['add_uid'];
			$list['add_date']=$r['add_date'];
			$list['name']=$r['name'];
			$list['type']=$r['type'];
			$db_new->add($list);
		}
		die("映射完毕!!!!"."upload表");
	}
	/*数据映射 old 商务谈判 到 new 商务进程记录*/
	public function data_map_negotiation(){
		$db_old=M('db_project_negotiation');
		$db_new=M('db_crm_follow_record');
		$result = $db_old->order("id asc")->select();
		$list = array();
		$type_list=array('工作建议书'=>'1','计划书沟通'=>'2','合同沟通'=>'3','接待,合同沟通'=>'3','接待,工作建议书'=>'1','电话沟通,合同沟通'=>'3','考察,工作建议书'=>'1','计划书沟通,合同沟通'=>'2,3','计划书沟通,工作建议书'=>'1,2');
		foreach($result as $r){
			$list['project_id']=$r['pid'];
			$list['visit_date']=$r['date'];
			$list['add_uid']=$r['add_uid'];
			$list['add_date']=$r['add_date'];
			$list['file_name']=$r['file_name'];
			$list['file_url']=$r['file_url'];
			$list['status']=2;//项目阶段--商务谈判
			$list['work_type']=$type_list[$r['type']];
			$list['work_chance']=1;//商务机会--顺利
			if($r['content']!=""){
				if($r['type_remark']!=""){
					$list['remark']=$r['content']."<br />".$r['type_remark'];
				}else{
					$list['remark']=$r['content'];
				}
			}else{
				if($r['type_remark']!=""){
					$list['remark']=$r['type_remark'];
				}
			}
			$list['contact_id']=$r['ocid'];
			$timeInfo = $this->getNowTimeInfo($r['add_date']);
			$list['year']=$timeInfo['year'];
			$list['week']=$timeInfo['week'];
			$list['year_week']=$timeInfo['year'].$timeInfo['week'];
			$db_new->add($list);
		}
		die("映射完毕!!!!"."negotiation表");
	}
	/*收入规则列表*/
	public function income_rule_list(){
		parent::check_permission('CRMI-R');//权限收入规则
        $db_contract = M("db_contract");
        $where['del'] = 1;
        // $where['status'] = 1;
        $project_id_array = $db_contract->where($where)->field('project_id')->select();
        $project_id_array = array_unique(array_column($project_id_array, 'project_id'));
        $crm_project_array = CrmProjectController::getCrmProjectArray($project_id_array);
        $project_id = I('project_id');
        if (!empty($project_id)) $where['project_id'] = $project_id;
		$check_base_id = I('check_base_id');
		if (!empty($check_base_id)) $other['base'] = $check_base_id;
		$check_float_id = I('check_float_id');
		if (!empty($check_float_id)) $other['float'] = $check_float_id;
        $contract = $db_contract->where($where)->order('add_date desc')->select();
        $project_ids = $this->column($contract, 'project_id');
        $project_ids = implode(',', $project_ids);
        $db_crm_project = M("db_crm_project");
        $project = $db_crm_project->where("project_id in ($project_ids) and stage!=6")->select();
		$db_income_rule = M("db_project_income_rule");
		$income_base_rule = $db_income_rule->field('rule_id,income_type as income_base,project_id')->where("project_id in ($project_ids) and income_type=1")->select();
		$income_float_rule = $db_income_rule->field('rule_id,income_type as income_float,project_id')->where("project_id in ($project_ids) and income_type=2")->select();
		$db_payment = M("db_project_income_payment");
		$income_payment_list = $db_payment->field('payment_id,project_id,payment_date')->where("project_id in ($project_ids)")->select();
		//->join('LEFT JOIN db_crm_project ON db_crm_project.project_id=db_project_income_rule.project_id')
        $result = array();
        foreach ($contract as $key => $value) {
			//获取对应的项目信息
            foreach ($project as $k => $v) {
                if ($value['project_id'] == $v['project_id']) {
				// if ($value['project_id'] == $v['project_id']) {
                    $result[] = array_merge($v, $value);
                }
            }
			if(!empty($result[$key])){
				$result[$key]['income_base']="";
				foreach ($income_base_rule as $k => $v) {
					if ($value['project_id'] == $v['project_id']) {
						$result[$key]['income_base'] = $v['income_base'];
						$result[$key]['base_rule_id'] = $v['rule_id'];
						$result[$key]['base_type'] = getIncomeType($v['rule_id'],2);
					}
				}
			}
			if(!empty($result[$key])){
				$result[$key]['income_float']="";
				foreach ($income_float_rule as $k => $v) {
					if ($value['project_id'] == $v['project_id']) {
						$result[$key]['income_float'] = $v['income_float'];
						$result[$key]['float_rule_id'] = $v['rule_id'];
						$result[$key]['float_type'] = getIncomeType($v['rule_id'],2);
					}
				}
			}
			if(!empty($result[$key])){
				$result[$key]['payment']='';
				foreach ($income_payment_list as $k => $v) {
					if ($value['project_id'] == $v['project_id']) {
						$result[$key]['payment'] = $v['payment_id'];
						$date = explode(" ",$v['payment_date']);
						$result[$key]['payment_date'] = $date[0];
					}
				}
			}
        }
		if($other['base']){
			foreach($result as $key=>$re){
				if($re['income_base']==''){
					unset($result[$key]);
				}else{
					if($re['base_type']!=$other['base']){
						unset($result[$key]);
					}
				}
			}
		}
		if($other['float']){
			foreach($result as $key=>$re){
				if($re['income_float']==''){
					unset($result[$key]);
				}else{
					if($re['float_type']!=$other['float']){
						unset($result[$key]);
					}
				}
			}
		}
		// print_r($result);
		// die("==8==");
		//分摊方式
		$apportion_type=$this->get_constant(C("APPORTION_TYPE"));
		//获取当前税率
		$rate = $this->getRate();
        $this->assign('result', $result);
        $this->assign('page', $show);
        $this->assign('project_id', $project_id);
        $this->assign('check_base_id', I('check_base_id'));
        $this->assign('check_float_id', I('check_float_id'));
        $this->assign('rate', $rate['rate']);
        $this->assign('rate_id', $rate['rate_id']);
        $this->assign('nowdate', explode(" ",$rate['change_date']));
        $this->assign('crm_project_array', $crm_project_array);
        $this->assign('apportion_type', $apportion_type);
        $this->display();
	}
	//税率规则相关的ajax操作
	public function income_rule_doadd(){
		if($_REQUEST['action']=='rate'){
			$add_data=array();
			$db_rate = M("db_project_rate");
			unset($_REQUEST['action']);
			$add_data = $this->unset_null($_REQUEST,$add_data);//清洗提交的空数据
            $add_data['add_uid'] = $_SESSION['dms_uid'];
            $add_data['add_user'] = $_SESSION['dms_username'];
            $add_data['add_date'] = date('Y-m-d H:i:s');
			$result_bool=$db_rate->add($add_data);
			//整体收入调整
			$this->income_rule($result_bool,$_REQUEST['old_rate']);
		}elseif($_REQUEST['action']=='income'){
			//规则入库
			$add_data=$add_data_detail=array();
			$db_rule = M("db_project_income_rule");
			$db_rule_detail = M("db_project_rule_detail");
			unset($_REQUEST['action']);
			$add_data['rate_id']=$_REQUEST['rate'];
			$add_data['project_id']=$_REQUEST['project_id'];
			$add_data['income_type']=$_REQUEST['rate_type'];
			$add_data['add_uid'] = $_SESSION['dms_uid'];
            $add_data['add_user'] = $_SESSION['dms_username'];
            $add_data['add_date'] = date('Y-m-d H:i:s');
			$result_bool=$db_rule->add($add_data);
			//规则明细入库
			$add_data_detail = array();
			foreach ($_REQUEST['amount'] as $k => $v) {
				if (!empty($v)) {
					$add_data_detail['apportion_type']=$_REQUEST['apportion_type'];
					$add_data_detail['rule_id']=$result_bool;
					$add_data_detail['start_date']=$_REQUEST['start_date'][$k];
					$add_data_detail['end_date']=$_REQUEST['end_date'][$k];
					$add_data_detail['amount']=$_REQUEST['amount'][$k];
					$add_data_detail['add_uid'] = $_SESSION['dms_uid'];
					$add_data_detail['add_user'] = $_SESSION['dms_username'];
					$add_data_detail['add_date'] = date('Y-m-d H:i:s');
					$db_rule_detail->add($add_data_detail);
				}
			}
			//规则明细入收入表
			$this->getIncomeToTable($_REQUEST);
		}elseif($_REQUEST['action']=='payment'){
			//检查是否有月分摊类规则
			$db_income_rule = M('db_project_income_rule');
			$db_payment = M('db_project_income_payment');
			$where['project_id']=$_REQUEST["pid"];
			$result = $db_income_rule->where($where)->select();
			if(!empty($result)){
				$add_data = array();
				$add_data['project_id']=$_REQUEST["pid"];
				$add_data['payment_date']=$_REQUEST["payment_date"];
				$add_data['add_uid'] = $_SESSION['dms_uid'];
				$add_data['add_user'] = $_SESSION['dms_username'];
				$add_data['add_date'] = date('Y-m-d H:i:s');
				$result_bool=$db_payment->add($add_data);
			}else{
				$data['status']=2;
				$data['msg']='该项目暂无规则,税调补差无意义';
				echo json_encode($data);die;
			}
		}

		if($result_bool)
		{
			$data['status']=self::YES;
			$data['msg']='操作成功';
		}
		else
		{
			$data['status']=self::NO;
			$data['msg']='操作失败';
		}
		echo json_encode($data);die;
	}
	//判断相隔月份
	public function calculateDate($start,$end){
		$st = explode("-",$start);
		$et = explode("-",$end);
		$time1 = strtotime($st[0]."-".$st[1]); // 自动为00:00:00 时分秒 两个时间之间的年和月份  
		$time2 = strtotime($et[0]."-".$et[1]);  
		   
		$monarr = array();  
		$monarr[] = $st[0]."-".$st[1]; // 当前月;  
		while( ($time1 = strtotime('+1 month', $time1)) <= $time2){  
			  $monarr[] = date('Y-m',$time1); // 取得递增月;   
		}  
		$arr['list']=$monarr;
		$arr['count']=count($monarr);
		return $arr;
	}
	//规则入明细表
	/*
		参数：$result 结果集
	*/
	public function getIncomeToTable($result){
		//获取当前税率
		$db_rate = M('db_project_rate');
		$re = $db_rate->field('rate,change_date')->where("rate_id={$result['rate']}")->find();
		//循环每期情况进行录入
		if($result['rate_type']==1){//按月还是浮动
			$db = M("db_project_income_month");
		}else{
			$db = M("db_project_income_kpi");
		}
		foreach ($result['amount'] as $k => $v) {
			$edit=array();
			if (!empty($v)) {
				if($result['apportion_type']==1){
					$start_date=$result['start_date'][$k];
					$end_date=$result['end_date'][$k];
					$timearr = $this->calculateDate($start_date,$end_date);
					$amount=round((($v / $re['rate']) / $timearr['count']),2);
					foreach($timearr['list'] as $t){
						$time = explode("-",$t);
						$month = $time[1];
						if($month[0]==1){
							$realmonth="m".$month;
						}else{
							$realmonth="m".$month[1];
						}
						$where="";
						$where['pid']=$result['project_id'];
						$where['year']=$time[0];
						$r = $db->where($where)->find();
						if(!empty($r)){
							if($result['rate_type']==1){
								$edit['imid']=$r['imid'];
							}else{
								$edit['id']=$r['id'];
							}
							$edit[$realmonth]=$amount;
							$edit['year']=$time[0];
							$db->save($edit);
						}else{
							$this->insertMonth($result['project_id'],$time[0],$realmonth,$amount);
						}
					}
				}else{
					$start_date=$result['start_date'][$k];
					$datetime = explode("-",$start_date);
					$month=$datetime[1];
					if($month[0]==1){
						$realmonth="m".$month;
					}else{
						$realmonth="m".$month[1];
					}
					$amount=round(($result['amount'][$k] / $re['rate']),2);
					$where="";
					$where['pid']=$result['project_id'];
					$where['year']=$datetime[0];
					$r = $db->where($where)->find();
					if(!empty($r)){//更新
						if($result['rate_type']==1){
							$edit['imid']=$r['imid'];
						}else{
							$edit['id']=$r['id'];
						}
						$edit[$realmonth]=$amount;
						$db->save($edit);
					}else{//添加
						$this->insertKpi($result['project_id'],$datetime[0],$realmonth,$amount);
					}
				}
			}
		}
	}
	//收入规则记录到kpi表
	public function insertKpi($pid,$year,$m,$mcount){
		$db_month = M("db_project_income_month");
		$db_kpi = M("db_project_income_kpi");
		$add = array();
		$add['pid']=$pid;
		$add['year']=$year;
		$db_month->add($add);
		$add[$m]=$mcount;
		$db_kpi->add($add);
	}
	public function insertMonth($pid,$year,$m,$mcount){
		$db_month = M("db_project_income_month");
		$db_kpi = M("db_project_income_kpi");
		$add=array();
		$add['pid']=$pid;
		$add['year']=$year;
		$db_kpi->add($add);
		$add[$m]=$mcount;
		$db_month->add($add);
	}
	public function getRuleByIncomeId(){
		$db_rule = M('db_project_income_rule');
		$where['rule_id']=$_REQUEST['id'];
		$re = $db_rule->where($where)->find();
		$db_rate = M('db_project_rate');
		$re_rate = $db_rate->where("rate_id={$re['rate_id']}")->find();
		$re['rate']=$re_rate['rate'];//获取税率该规则制定时候的
		//获取规则详细
		$db_rule_detail = M('db_project_rule_detail');
		$re_detail = $db_rule_detail->where("rule_id={$re['rule_id']}")->select();
		$html="";
		foreach($re_detail as $rd){
			if($rd['apportion_type']==1){
				$start = explode(" ",$rd['start_date']);
				$end = explode(" ",$rd['end_date']);
				$html .= '<tr><td class="fbold" width="200"><strong class="red">*</strong>确认日期</td><td><input type="text" value="'.$start[0].'" name="start_date[]" class="form-control Wdate required-text1 w100 start_date" onclick="WdatePicker()" readonly><span class="error-item">必填项</span><label class="fuhao">~</label><input type="text" value="'.$end[0].'" name="end_date[]" class="form-control Wdate required-text1 w100 end_date" onclick="WdatePicker()" readonly><span class="error-item">必填项</span></td></tr><tr><td class="fbold income_name"><strong class="red">*</strong>基础管理费</td><td><input type="text" name="amount[]" value="'.$rd['amount'].'" class="form-control required-text1 rate" onkeyup="num(this);"><span class="error-item">必填项</span></td></tr>';
			}else{
				$start = explode(" ",$rd['start_date']);
				$html .= '<tr><td class="fbold" width="200"><strong class="red">*</strong>确认日期</td><td><input type="text" value="'.$start[0].'" name="start_date[]" class="form-control Wdate required-text1 w100 start_date" onclick="WdatePicker()" readonly><span class="error-item">必填项</span></td></tr><tr><td class="fbold income_name"><strong class="red">*</strong>浮动收益</td><td><input type="text" name="amount[]" value="'.$rd['amount'].'" class="form-control required-text1 rate" onkeyup="num(this);"><span class="error-item">必填项</span></td></tr>';
			}
		}
		$re['rule_info']=$html;
		echo json_encode($re);die;
	}
	/*
		税率调整执行
		参数
	*/
	public function income_rule($nrate=0,$orate=0){
		$db_rate = M('db_project_rate');
		$re = $db_rate->field('rate,change_date')->where("rate_id={$nrate}")->find();
		$change_date=explode(" ",$re['change_date']);//税率调整时间
		$change_date = explode("-",$change_date[0]);
		$change_year = $change_date[0];//调税年
		$change_month = $change_date[1];//调税月
		$new_rate = $re['rate'];//最新税率
		$old_rate = $orate;
		$where="";
		//全项目循环月收入报表
		$db_month = M("db_project_income_month");
		$db_kpi = M("db_project_income_kpi");
		$db_project_bg = M("db_project_bg");
		$db_receipt = M("db_contract_receipt");
		$db_payment = M("db_project_income_payment");
		//循环获取每个项目的开发票情况
		$result_fp = $db_month->field('pid')->where($where)->group('pid')->select();
		$str = array();
		foreach($result_fp as $fp){
			$result_project_bg = $db_project_bg->field('bus_id')->where("pid={$fp['pid']}")->find();
			// $result_receipt = $db_receipt->field('MAX(date) as last')->where("project_id={$result_project_bg['bus_id']}")->find();
			$result_payment = $db_payment->field('payment_date as pdate')->where("project_id={$result_project_bg['bus_id']}")->find();
			// if(!empty($result_receipt['last'])){
				// $result_receipt = explode("-",$result_receipt['last']);
				// $str[$fp['pid']]['receipt_year']=$result_receipt[0];
				// $str[$fp['pid']]['receipt_month']=$result_receipt[1];
			// }else{
				// $str[$fp['pid']]['receipt_year']="";
				// $str[$fp['pid']]['receipt_month']="";
			// }
			if(!empty($result_payment['pdate'])){
				$result_pdate = explode("-",$result_payment['pdate']);
				$str[$fp['pid']]['payment_year']=$result_pdate[0];
				$str[$fp['pid']]['payment_month']=$result_pdate[1];
			}
		}
		$order="pid desc,year asc";
		
		$result = $db_month->where($where)->order($order)->select();
		$result_kpi = $db_kpi->where($where)->order($order)->select();
		foreach($result as $key=>$r){
			if($str[$r['pid']]['payment_year']){//设置了补差时间（补差日期以后时间按照新税率调整），补差之前及补差当月不变，通过收入调整微调
				$payment_year = $str[$r['pid']]['payment_year'];
				if($r['year']==$payment_year){//和补差时间同月，定位具体月份
					$payment_month = $str[$r['pid']]['payment_month'];
					if($payment_month!=12){//整行不改
						$this->checkMonth($payment_month,$result[$key],array($old_rate,$new_rate));
					}
				}else{
					if($r['year']-$payment_year > 0){
						$this->changeRate($result[$key],array($old_rate,$new_rate));
					}
				}
			}else{
				// if($str[$r['pid']]['receipt_year']){
					//有开票的数据，开票月及之前月份不变，后面的调整暂时不用
					// $receipt_year = $str[$r['pid']]['receipt_year'];
					// if($r['year']==$receipt_year){
						// $receipt_month = $str[$r['pid']]['receipt_month'];
						// if($receipt_month!=12){//整行不改
							// $this->checkMonth($receipt_month,$result[$key],array($old_rate,$new_rate));
						// }
					// }else{
						// if($r['year']-$receipt_year > 0){
							// $this->changeRate($result[$key],array($old_rate,$new_rate));
						// }
					// }
					if($r['year']==$change_year){
						if($change_month!=12){//整行不改
							$this->checkMonth($change_month,$result[$key],array($old_rate,$new_rate));
						}
					}else{
						if($r['year']-$change_year > 0){
							$this->changeRate($result[$key],array($old_rate,$new_rate));
						}
					}
				// }else{//无开票全数据改
					// $this->changeRate($result[$key],array($old_rate,$new_rate));
				// }
			}
		}

		//全项目循环kpi表
		foreach($result_kpi as $key=>$rk){
			if($rk['year']==$change_year){
				if($change_month!=12){//整行不改
					$this->checkMonthKpi($change_month,$result_kpi[$key],array($old_rate,$new_rate));
				}
			}else{
				if($rk['year']-$change_year > 0){
					$this->changeRate($result_kpi[$key],array($old_rate,$new_rate),1);
				}
			}
			// if($str[$rk['pid']]['receipt_year']){//有开票的数据，开票月之前月份不变，当月及后面的调整
				// $receipt_year = $str[$rk['pid']]['receipt_year'];
				// if($rk['year']==$receipt_year){
					// $receipt_month = $str[$rk['pid']]['receipt_month'];
					// $this->checkMonthKpi($receipt_month,$result_kpi[$key],array($old_rate,$new_rate));
				// }else{
					// if($rk['year']-$receipt_year > 0){
						// $this->changeRate($result_kpi[$key],array($old_rate,$new_rate),1);
					// }
				// }
			// }else{
				// $this->changeRate($result_kpi[$key],array($old_rate,$new_rate),1);
			// }
		}
	}
	//阶段计算
	public function changeRate($r,$rule=array(),$type=0){
		$str_edit=array();
		if($type==0){
			$db = M("db_project_income_month");
			$str_edit['imid']=$r['imid'];
		}else{
			$db = M("db_project_income_kpi");
			$str_edit['id']=$r['id'];
		}
		if(!empty($r['m1'])){$str_edit['m1']=round(($r['m1'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m2'])){$str_edit['m2']=round(($r['m2'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m3'])){$str_edit['m3']=round(($r['m3'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
		if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
		$db->save($str_edit);
	}
	public function checkMonth($month,$r,$rule){
		$db_month = M("db_project_income_month");
		$str_edit=array();
		$str_edit['imid']=$r['imid'];
		if($month[0]==0){
			if($month[1]==1){
				if(!empty($r['m2'])){$str_edit['m2']=round(($r['m2'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m3'])){$str_edit['m3']=round(($r['m3'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==2){
				if(!empty($r['m3'])){$str_edit['m3']=round(($r['m3'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==3){
				if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==4){
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==5){
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==6){
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==7){
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==8){
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==9){
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}	
		}elseif($month[0]==1){
			if($month[1]==0){//10月
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==1){//11月
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}
		}
		$db_month->save($str_edit);
	}
	public function checkMonthKpi($month,$r,$rule){
		$db_month = M("db_project_income_kpi");
		$str_edit=array();
		$str_edit['id']=$r['id'];
		if($month[0]==0){
			if($month[1]==1){
				if(!empty($r['m1'])){$str_edit['m1']=round(($r['m1'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m2'])){$str_edit['m2']=round(($r['m2'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m3'])){$str_edit['m3']=round(($r['m3'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==2){
				if(!empty($r['m2'])){$str_edit['m2']=round(($r['m2'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m3'])){$str_edit['m3']=round(($r['m3'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==3){
				if(!empty($r['m3'])){$str_edit['m3']=round(($r['m3'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==4){
				if(!empty($r['m4'])){$str_edit['m4']=round(($r['m4'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==5){
				if(!empty($r['m5'])){$str_edit['m5']=round(($r['m5'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==6){
				if(!empty($r['m6'])){$str_edit['m6']=round(($r['m6'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==7){
				if(!empty($r['m7'])){$str_edit['m7']=round(($r['m7'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==8){
				if(!empty($r['m8'])){$str_edit['m8']=round(($r['m8'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==9){
				if(!empty($r['m9'])){$str_edit['m9']=round(($r['m9'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}	
		}elseif($month[0]==1){
			if($month[1]==0){//10月
				if(!empty($r['m10'])){$str_edit['m10']=round(($r['m10'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==1){//11月
				if(!empty($r['m11'])){$str_edit['m11']=round(($r['m11'] * $rule[0] / $rule[1]),2);}
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}elseif($month[1]==2){
				if(!empty($r['m12'])){$str_edit['m12']=round(($r['m12'] * $rule[0] / $rule[1]),2);}
			}
		}
		$db_month->save($str_edit);
	}
	//获取税率
	public function getRate(){
		$db_rate = M("db_project_rate");
		$result = $db_rate->field('rate,rate_id,change_date')->order("rate_id desc")->find();
		return $result;
	}
	public static function column(array $array, $columnName)
    {
        if (empty($array)) {
            return array();
        }

        $column = array();

        foreach ($array as $item) {
            if (isset($item[$columnName])) {
                $column[] = $item[$columnName];
            }
        }
        return $column;
    }
	/*月收入报表*/
	public function income_month(){
		parent::check_permission('CRMM-R');//权限收入报表
		if(!empty($_REQUEST['check_project_id'])){$pid=$_REQUEST['check_project_id'];}else{$pid="";}
		if(!empty($_REQUEST['check_year'])){$check_year=$_REQUEST['check_year'];}else{$check_year="";}
		$db_month = M("db_project_income_month");
		$where="";
		$order="pid desc,year asc";
		$field="imid,pid,year,m1,m2,m3,m4,m5,m6,m7,m8,m9,m10,m11,m12";
		if($pid!=""){//过滤项目
			$where['pid']=$pid;
		}
		if($check_year!=""){//过滤年份
			$where['year']=$check_year;
		}
		$result = $db_month->field($field)->where($where)->order($order)->select();
		$res=array();
		$group_order="pid";
		$field_order="imid,count(*) as count,pid";
		$result_order= $db_month->field($field_order)->where($where)->group($group_order)->order('pid desc')->select();
		foreach($result_order as $ro){
			$res[$ro['pid']]['count']=$ro['count'];
			$res[$ro['pid']]['pid']=$ro['pid'];
			$res[$ro['pid']]['imid']=$ro['imid'];
		}
		//年份过滤
		$result_year = $db_month->field('year')->group('year')->select();
		//项目名过滤
		$result_pid = $db_month->field('pid')->group('pid')->select();
		$result_pid_list = $this->getAllProjectNameByIncome($result_pid);
		$result_sum = getIncomeAll($pid,$check_year);
		$this->assign('result', $result);
		$this->assign('result_order', $res);
		$this->assign('result_year', $result_year);
		$this->assign('result_sum', $result_sum);
		$this->assign('result_pid_list', $result_pid_list);
		$this->assign('check_project_id',$pid);//总列表选中的项目
		$this->assign('check_year',$check_year);//总列表选中的年份
		if($check_year!="" || $pid!=""){
			$this->assign('result_num',count($result));
			$this->display('income_month_order');
		}else{
			$this->display('income_month');
		}
	}
	/*调整收入按项目+年份*/
	public function income_change(){
		parent::check_permission('CRMM-R');//权限收入报表
		$imid = $_GET['imid'];
		$where_kpi="";
		$db_month = M("db_project_income_month");
		$db_kpi = M("db_project_income_kpi");
        $result = $db_month->where("imid=$imid")->find();
		foreach($result as $k=>$re){
			if($k=="imid"){
				$result[$k]=$this->getProjectNameByIncome($re['pid']);
			}
		}
		$where_kpi['pid']=$result['pid'];
		$where_kpi['year']=$result['year'];
		$result_kpi = $db_kpi->where($where_kpi)->find();
        if (!empty($_POST)) {
            try{
				//修改月收入和KPI
				$this->month_save($_POST);
				$this->kpi_save($_POST);
				$this->success('修改成功',__APP__."/Crm/income_month");die;
            }catch (\Exception $e){
                $this->add_log('修改市场信息失败','');
				$this->error("操作失败", __APP__ . "/Crm/income_change/imid/{$imid}");
            }
        }
        $this->assign('result', $result);
        $this->assign('result_kpi', $result_kpi);
        $this->assign('imid',$imid);
        $this->assign('imid_kpi',$result_kpi['id']);
		$this->display();
	}
	/*调整收入按项目*/
	public function income_change_by_pid(){
		parent::check_permission('CRMM-R');//权限收入报表
		$pid = $_GET['pid'];
		$db_month = M("db_project_income_month");
		$result = $db_month->where("pid=$pid")->select();
		$res=array();
		$group_order="pid";
		$field_order="imid,count(*) as count,pid";
		$result_order= $db_month->field($field_order)->where($where)->group($group_order)->order('pid desc')->select();
		foreach($result_order as $ro){
			$res[$ro['pid']]['count']=$ro['count'];
			$res[$ro['pid']]['pid']=$ro['pid'];
			$res[$ro['pid']]['imid']=$ro['imid'];
		}
		$add_data = array();
		if (!empty($_POST)) {
            try{
				$this->checkInfo($_POST);
				$this->success('修改成功',__APP__."/Crm/income_month");die;
            }catch (\Exception $e){
                $this->add_log('修改市场信息失败','');
				$this->error("操作失败", __APP__ . "/Crm/income_change_by_pid/pid/{$pid}");
            }
        }
		$this->assign('result_order', $res);
		$this->assign('result', $result);
		$this->assign('pid', $pid);
		$this->display();

	}
	/*
		参数:	$re	结果集
				$pid 对应的项目id
	*/	
	public function checkInfo($re){
		$list = $re['imid'];
		$str=array();
		foreach($list as $l){
			$info = explode("_",$l);
			//拿到自增id
			$imid = $info[1];
			$year = $info[0];
			//拿到更新的值
			$str[$year]['imid']=$imid;
			foreach($re as $k=>$r){
				$key = explode("_",$k);
				if($year==$key[0]){
					if($r!=""){
						$str[$year][$key[1]]=$r;
					}else{
						$str[$year][$key[1]]=NULL;
					}
				}
			}
		}
		foreach($str as $ke=>$s){
			$this->month_save($s);
			$this->change_kpi($s['imid'],$s['kpi'],$ke);
		}
	}
	public function month_save($result){
		$db_month = M("db_project_income_month");
		$edit_data = array();
		$edit_data['imid']=$result['imid'];
		$edit_data['m1']=(!empty($result['m1']))?$result['m1']:NULL;
		$edit_data['m2']=(!empty($result['m2']))?$result['m2']:NULL;
		$edit_data['m3']=(!empty($result['m3']))?$result['m3']:NULL;
		$edit_data['m4']=(!empty($result['m4']))?$result['m4']:NULL;
		$edit_data['m5']=(!empty($result['m5']))?$result['m5']:NULL;
		$edit_data['m6']=(!empty($result['m6']))?$result['m6']:NULL;
		$edit_data['m7']=(!empty($result['m7']))?$result['m7']:NULL;
		$edit_data['m8']=(!empty($result['m8']))?$result['m8']:NULL;
		$edit_data['m9']=(!empty($result['m9']))?$result['m9']:NULL;
		$edit_data['m10']=(!empty($result['m10']))?$result['m10']:NULL;
		$edit_data['m11']=(!empty($result['m11']))?$result['m11']:NULL;
		$edit_data['m12']=(!empty($result['m12']))?$result['m12']:NULL;
		$db_month->save($edit_data);
	}
	//调整收入kpi字段（按月调整）
	public function kpi_save($result){
		$db_kpi = M("db_project_income_kpi");
		$edit_data=array();
		$edit_data['id']=$result['imid_kpi'];
		$edit_data['m1']=(!empty($result['m1f']))?$result['m1f']:NULL;
		$edit_data['m2']=(!empty($result['m2f']))?$result['m2f']:NULL;
		$edit_data['m3']=(!empty($result['m3f']))?$result['m3f']:NULL;
		$edit_data['m4']=(!empty($result['m4f']))?$result['m4f']:NULL;
		$edit_data['m5']=(!empty($result['m5f']))?$result['m5f']:NULL;
		$edit_data['m6']=(!empty($result['m6f']))?$result['m6f']:NULL;
		$edit_data['m7']=(!empty($result['m7f']))?$result['m7f']:NULL;
		$edit_data['m8']=(!empty($result['m8f']))?$result['m8f']:NULL;
		$edit_data['m9']=(!empty($result['m9f']))?$result['m9f']:NULL;
		$edit_data['m10']=(!empty($result['m10f']))?$result['m10f']:NULL;
		$edit_data['m11']=(!empty($result['m11f']))?$result['m11f']:NULL;
		$edit_data['m12']=(!empty($result['m12f']))?$result['m12f']:NULL;
		$db_kpi->save($edit_data);
	}
	//调整收入kpi字段
	/*
		参数:$id		db_project_income_kpi表中的id
			 $kpi       kpi值变化
			 $year		年份值
		备注：按项目调整收入设置的kpi都统一累计到kpi表12月份
	*/
	public function change_kpi($id,$kpi,$year){
		$db_kpi = M("db_project_income_kpi");
		$edit_data=array();
		$edit_data['id']=$id;
		$edit_data['year']=$year;
		$edit_data['m12']=$kpi;
		$db_kpi->save($edit_data);
	}
	/*月收入表导出*/
	public function income_export(){
		parent::check_permission('CRMM-R');//权限收入报表
		if(!empty($_REQUEST['check_project_id'])){$pid=$_REQUEST['check_project_id'];}else{$pid="";}
		if(!empty($_REQUEST['check_year'])){$check_year=$_REQUEST['check_year'];}else{$check_year="";}
		$db_month=M('db_project_income_month');
		$where="";
		$order="pid desc,year asc";
		$field="pid,year,m1,m2,m3,m4,m5,m6,m7,m8,m9,m10,m11,m12";
		if($pid!=""){//过滤项目
			$where['pid']=$pid;
		}
		if($check_year!=""){//过滤年份
			$where['year']=$check_year;
		}
		$result = $db_month->field($field)->where($where)->order($order)->select();
		//数据处理
		foreach($result as $key=>$re){
			//项目编号-名称
			$result[$key]['pid']=$this->getProjectNameByIncome($re['pid']);
			//kpi
			$result[$key]['kpi']=getProjectKpiByIncome($re['pid'],$re['year']);
			//合计
			$result[$key]['sum']=getProjectSumYearByIncome($re['pid'],$re['year']);
		}
		$headName = "收入月报表";
		$headArr = array("项目名称","年份","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月","KPI","合计");
		$this->downloaddExcel($headName,$headArr,$result);
	}
	/*映射收入表的数据*/
	public function data_map_income_month(){
		$db_month = M("db_project_income_month");
		$db_old= M("db_project_bg");
		$order="pid desc,year asc";
		$result = $db_month->field('imid,pid')->order($order)->select();
		foreach($result as $key=>$re){
			//项目编号-名称
			$edit = $where = array();
			$where['pid']=$re['pid'];
			$result_old = $db_old->field('bus_id')->where($where)->find();
			$edit['imid']=$re['imid'];
			$edit['pid']=$result_old['bus_id'];
			$db_month->save($edit);
		}
		die("映射完毕!!!!"."income_month表");
	}
	public function data_map_income_kpi(){
		$db_kpi = M("db_project_income_kpi");
		$db_old= M("db_project_bg");
		$order="pid desc,year asc";
		$result = $db_kpi->field('id,pid')->order($order)->select();
		foreach($result as $key=>$re){
			//项目编号-名称
			$edit = $where = array();
			$where['pid']=$re['pid'];
			$result_old = $db_old->field('bus_id')->where($where)->find();
			$edit['id']=$re['id'];
			$edit['pid']=$result_old['bus_id'];
			$db_kpi->save($edit);
		}
		die("映射完毕!!!!"."income_kpi表");
	}
	public function data_map_income(){
		$db = M("db_project_income");
		$db_old= M("db_project_bg");
		$order="pid desc,year asc";
		$result = $db->field('income_id,project_id')->order($order)->select();
		foreach($result as $key=>$re){
			//项目编号-名称
			$edit = $where = array();
			$where['pid']=$re['project_id'];
			$result_old = $db_old->field('bus_id')->where($where)->find();
			$edit['income_id']=$re['id'];
			$edit['project_id']=$result_old['bus_id'];
			$db->save($edit);
		}
		die("映射完毕!!!!"."income表");
	}
}





















?>